<?php
// 自定义success助手函数
use think\facade\Request;
use think\facade\Db;
if (!function_exists('save_log')) {
    function save_log ($msg, $type = 0, $param = 0)
    {
        $log_data = array(
            'log_info' => $msg,
            'log_time' => time(),
            'log_user' => session('admin.admin_id'),
            'log_ip' => get_client_ip(),
            'log_type' => $type,
            'log_controller' => Request()->controller(),
            'log_action' => Request()->action(),
        );
        if ($param) $log_data['log_param'] = serialize($_REQUEST);
        Db::name('log')->insert($log_data);
    }
}

if (!function_exists('get_client_ip')) {
    function get_client_ip ($type = 0, $adv = false)
    {
        $type = $type ? 1 : 0;
        static $ip = NULL;
        if ($ip !== NULL) return $ip[$type];
        if ($adv) {
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                $pos = array_search('unknown', $arr);
                if (false !== $pos) unset($arr[$pos]);
                $ip = trim($arr[0]);
            } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $ip = $_SERVER['HTTP_CLIENT_IP'];
            } elseif (isset($_SERVER['REMOTE_ADDR'])) {
                $ip = $_SERVER['REMOTE_ADDR'];
            }
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u", ip2long($ip));
        $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }
}
function success($msg = '成功', $url = '')
{
    $data['status'] = 200;
    $data['msg'] = $msg;
    $data['url'] = $url;
    return json($data);
}

// 自定义successIframe助手函数
function successIframe($msg = '成功', $url = '')
{
    $data['status'] = 201;
    $data['msg'] = $msg;
    return json($data);
}

// 自定义error助手函数
function error($msg = '失败', $url = '')
{
    $data['status'] = 202;
    $data['msg'] = $msg;
    $data['url'] = $url;
    return json($data);
}

function AdminGroup($cate , $pid = 0,$rules){
    $arr = array();
    $rulesArr = explode(',',$rules);
    foreach ($cate as $v){
        if ($v['pid'] == $pid) {
            if (in_array($v['id'], $rulesArr)) {
                $v['checked'] = true;
            }
            $v['open'] = true;
            $arr[]=$v;
            $arr = array_merge($arr, AdminGroup($cate, $v['id'], $rules));
        }
    }
    return $arr;
}


function articate_tree($articate , $lefthtml = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|— ' , $pid=0 , $lvl=0 ){
    $arr=array();
    foreach ($articate as $v){
        if($v['parentid']==$pid){
            $v['lvl']=$lvl + 1;
            $v['lefthtml']=str_repeat($lefthtml,$lvl);
            $v['artname']=$v['lefthtml'].$v['articlecatename'];
            $arr[]=$v;
            $arr= array_merge($arr,articate_tree($articate,$lefthtml,$v['art_id'], $lvl+1 ));
        }
    }
    return $arr;
}

function page_tree($articate , $lefthtml = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|— ' , $pid=0 , $lvl=0 ){
    $arr=array();
    foreach ($articate as $v){
        if($v['parentid']==$pid){
            $v['lvl']=$lvl + 1;
            $v['lefthtml']=str_repeat($lefthtml,$lvl);
            $v['pagename']=$v['lefthtml'].$v['pagecatename'];
            $arr[]=$v;
            $arr= array_merge($arr,page_tree($articate,$lefthtml,$v['page_id'], $lvl+1 ));
        }
    }
    return $arr;
}

function goodscate_tree($goodscate , $lefthtml = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|— ' , $pid=0 , $lvl=0 ){
    $arr=array();
    foreach ($goodscate as $v){
        if($v['parentid']==$pid){
            $v['lvl']=$lvl + 1;
            $v['lefthtml']=str_repeat($lefthtml,$lvl);
            $v['goodscatename']=$v['lefthtml'].$v['goodscatename'];
            $arr[]=$v;
            $arr= array_merge($arr,goodscate_tree($goodscate,$lefthtml,$v['gcate_id'], $lvl+1 ));
        }
    }
    return $arr;
}

function category_tree($category , $lefthtml = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|— ' , $pid=0 , $lvl=0 ){
    $arr=array();
    foreach ($category as $v){
        if($v['parentid']==$pid){
            $v['lvl']=$lvl + 1;
            $v['lefthtml']=str_repeat($lefthtml,$lvl);
            $v['lcatname']=$v['lefthtml'].$v['categoryname'];
            $arr[]=$v;
            $arr= array_merge($arr,category_tree($category,$lefthtml,$v['id'], $lvl+1 ));
        }
    }
    return $arr;
}

/*检查复选框是否被选中*/
function is_checked($str = '', $id = 0){
    //dump($id);die;
    if(empty($str) || empty($id)){
        return false;
    }

    $arry = explode(",",$str);
    if(is_array($arry)){
        $res = in_array($id, $arry);
    }else{
        if($arry == $id){
            $res = true;
        }else{
            $res = false;
        }
    }

    return $res;
}

function getTemplate(){
    //查找设置的模版
    $path = './Template/'.config('site.WEB_STYLE').'/'.config('site.HTML').'/';
    //dump($path);die;
    $tpl['list'] = get_file_folder_List($path , 2, '*_list*');
    $tpl['show'] = get_file_folder_List($path , 2, '*_show*');
    return $tpl;
}

function get_file_folder_List($pathname, $fileFlag = 0, $pattern = '*'){
    $fileArray = array();
    $pathname  = rtrim($pathname, '/') . '/';
    $list      = glob($pathname . $pattern);
    foreach ($list as $i => $file) {
        switch ($fileFlag) {
            case 0:
                $fileArray[] = basename($file);
                break;
            case 1:
                if (is_dir($file)) {
                    $fileArray[] = basename($file);
                }
                break;

            case 2:
                if (is_file($file)) {
                    $fileArray[] = basename($file);
                }
                break;

            default:
                break;
        }
    }

    if (empty($fileArray)) {
        $fileArray = null;
    }

    return $fileArray;
}

function string2array($info)
{
    if ($info == '') return array();
    eval("\$r = $info;");
    return $r;
}



function get_dateran($dateran){
    if ($dateran) {
        $dateran = explode(" 至 ",$dateran);
    }
    if (is_array($dateran) && count($dateran) == 2) {
        $dateran[0] = strtotime($dateran[0]);
        $dateran[1] = strtotime($dateran[1])+24*60*60-1;
    }
    return $dateran;
}

//递归获取所有的子分类的ID
function get_all_child($array,$id){
    $arr = array();
    foreach($array as $v){
        if($v['parentid'] == $id){
            $arr[] = $v['id'];
            $arr = array_merge($arr,get_all_child($array,$v['id']));
        };
    };
    return $arr;
}



function config_setup($config)
{
    foreach ($config as $k => $v) {
        if ($config[$k]['setup']) {
            $config[$k]['setup'] = string2array($v['setup']);
            if (array_key_exists('options', $config[$k]['setup'])) {
                $config[$k]['setup']['options'] = explode("\n", $config[$k]['setup']['options']);
                foreach ($config[$k]['setup']['options'] as $kk => $vv) {
                    $config[$k]['setup']['options'][$kk] = array_element(explode("|", $config[$k]['setup']['options'][$kk]));

                }
            }
        }
    }
    return $config;
}

function array_element($array)
{
    if (!is_array($array))
        return trim($array);
    return array_map('array_element', $array);
}

function get_password($password, $encrypt = '')
{
    $pwd             = array();
    $pwd['encrypt']  = $encrypt ? $encrypt : get_randomstr();
    $pwd['password'] = md5(md5(trim($password)) . $pwd['encrypt']);
    return $encrypt ? $pwd['password'] : $pwd;
}

function get_randomstr($lenth = 6)
{
    return get_random($lenth, '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');
}

function get_random($length, $chars = '0123456789')
{
    $hash = '';
    $max  = strlen($chars) - 1;
    for ($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}





function format_bread_crumb($data)
{
    $result = array();
    if (!empty($data)) {
        $data = array_reverse($data);
        if (count($data) == 4) {
            //非常规 添加或修改
            $result['right'] = $data[1];
            $result['left'][0] = $data[1]['title'];
            //查看是添加还是修改
            $result['left'][1] = $data[2]['title'] . '-' . str_replace('操作-', '', $data[3]['title']);
        } else if (count($data) == 3) {
            //常规 添加或修改
            $result['right'] = $data[1];
            $result['left'][0] = $data[1]['title'];
            //查看是添加还是修改
            $result['left'][1] = str_replace('操作-', '', $data[2]['title']);
        } else if (count($data) == 2) {
            //常规 列表
            $result['right'] = $data[1];
            $result['left'][0] = $data[1]['title'];
            $result['left'][1] = '列表';
        } else {
            //单独定义
            $result['right'] = $data[0];
            $result['left'][0] = $data[0]['title'];
            $result['left'][1] = '';
        }
    }



    return $result;
}

function getChildsRule($rules, $pid)
{
    $arr = [];
    foreach ($rules as $v) {
        if ($v['pid'] == $pid) {
            $arr[] = $v;
            $arr = array_merge($arr, getChildsRule($rules, $v['id']));
        }
    }
    return $arr;
}

/**
 * 循环删除目录和文件
 * @param string $dir_name
 * @return bool
 */
function delete_dir_file($dir_name) {
    $result = false;
    if(is_dir($dir_name)){
        if ($handle = opendir($dir_name)) {
            while (false !== ($item = readdir($handle))) {
                if ($item != '.' && $item != '..') {
                    if (is_dir($dir_name . '/' . $item)) {
                        delete_dir_file($dir_name . '/' . $item);
                    } else {
                        unlink($dir_name . '/' . $item);
                    }
                }
            }
            closedir($handle);
            if (rmdir($dir_name)) {
                $result = true;
            }
        }
    }
    return $result;
}




